let fs = require('fs')
let request = require('request')
let requestList1 = [ ]

let api = 'https://douyin.dy114.com/parse/index'

const getData = async (item) => {
  const options = {
    url: api, // 替换为您要发送请求的 URL  
    method: 'POST',
    headers: {
      'Accept': 'application/json, text/javascript, */*; q=0.01',
      'Accept-Encoding': 'gzip, deflate, br',
      'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
      'Connection': 'keep-alive',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
      'Cookie': "Hm_lvt_b5ae0a50c43eeaa3321c86b7607d82e8=1698030573; Hm_lpvt_b5ae0a50c43eeaa3321c86b7607d82e8=1698030573",
      'Host': 'douyin.dy114.com',
      'Origin': 'https://douyin.dy114.com',
      'Referer': 'https://douyin.dy114.com/',
      'Sec-Fetch-Dest': "empty",
      'Sec-Fetch-Mode': "cors",
      'Sec-Fetch-Site': 'same-origin',
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0',
    },
    formData: {
      pageUrl: item,
    },
  };
  request(options, async (error, response) => {
    if (error) {
      console.error('请求出错:', error);
    } else {
      let res = JSON.parse(response.body)
      if (res.status == '200') {
        let name = res.data.data.title.split('#')[0]
        name = name.slice(0, name.length - 1)
        console.log(name);
        let url = res.data.data.voideurl
        await saveVideo(name, url)
      }
    }
  });
}

const list = async (requestList) => {
  for (let i = 0; i < requestList.length; i++) {
    (function(i) {
      setTimeout(async () => {
        await getData(requestList[i])
        console.log(requestList[i]);
      }, (i + 1) * 2000);
    })(i)
  }
}

const saveVideo = async (name, url) => {
  request(url).pipe(fs.createWriteStream('./videoDownload/' + name + '.mp4'))
}
list(requestList1)